<?php
class category_commonModel extends Model{
	protected function get_arrparentid($catid, $arrparentid = '', $n = 1) {
		if($n > 10 || !is_array($this->categorys) || !isset($this->categorys[$catid])) return false;
		$parentid = $this->categorys[$catid]['parentid'];
		$arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
		if($parentid) {
			$arrparentid = $this->get_arrparentid($parentid, $arrparentid, ++$n);
		} else {
			$this->categorys[$catid]['arrparentid'] = $arrparentid;
		}
		$parentid = $this->categorys[$catid]['parentid'];
		return $arrparentid;
	}
	protected function get_arrchildid($catid) {
		$arrchildid = $catid;
		if(is_array($this->categorys)) {
			foreach($this->categorys as $id => $cat) {
				if($cat['parentid'] && $id != $catid && $cat['parentid']==$catid) {
					$arrchildid .= ','.$this->get_arrchildid($id);
				}
			}
		}
		return $arrchildid;
	}
	public function cache(){
		$out=array();
		
		$categorys=$this->all_cats();
		
		$this->categorys=ka_builder($categorys,'catid');
		
		//删除在非正常显示的栏目
		//foreach($this->categorys as $catid => $cat) {
		//	if($cat['parentid'] != 0 && !isset($this->categorys[$cat['parentid']])) {
		//		$this->where(array('catid'=>$catid))->delete();
		//	}
		//}
		
		
		
		foreach($this->categorys as $catid => $cat) {
			$arrparentid = $this->get_arrparentid($catid);
			$arrchildid = $this->get_arrchildid($catid);
			$child = is_numeric($arrchildid) ? 0 : 1;
			$tmp=array();
			$tmp=array_merge($tmp,$cat);
			$tmp['arrparentid']=$arrparentid;
			$tmp['arrchildid']=$arrchildid;
			$tmp['child']=$child;
			
			$out[$catid]=$tmp;
		}

		
		$file=APPPATH.'runtime/category_cache/'.$this->table.'.php';
		return array_save($out,$file);
	}

	public function add($data){
		$this->action='add';
		$this->parentid=$data['parentid'];
		return $this->easy_insert($data);
	}
	public function mod($catid,$data){
		$this->action='mod';
		$this->catid=$catid;
		$this->parentid=$data['parentid'];
		if(!$this->mod_check_ok($catid,$data['parentid'])){
			msg(0,'不能将分类放置到当前分类或其子分类');
		}
		return $this->where(array('catid'=>$catid))->easy_update($data);
	}
	public function del($catid){
		if(!$this->del_check_ok($catid)){
			msg(0,'该分类下面还包含其他分类，先删除其子分类');
		}
		//信息
		$count=$this->get_sub_count($catid);
		if($count>0){
			msg(0,'该分类下面存在数据，请先清空数据');
		}
		return $this->where(array('catid'=>$catid))->easy_delete();
	}
	public function get_cat($catid){
		$catid=intval($catid);
		return $this->where(array('catid'=>$catid))->easy_find();
	}
	public function get_category($catid=''){
		$file=APPPATH.'runtime/category_cache/'.$this->table.'.php';
		$d=include($file);
		return $catid?$d[$catid]:$d;
	}
    public function get_sub_count($catid,$table){
        $sql="SELECT count(*) A FROM {$table} where catid='{$catid}'";
		return $this->db->get_field($sql);
    }
	public function cat_pos($CAT) {
		$str = ' &raquo; ';
		$target='';
		$db=$this->db;
		if(!$CAT) return '';
		$TMP=$this->get_category($CAT['catid']);
		$CAT=array_merge((array) $TMP,$CAT);
		
		if(!isset($CAT['arrparentid'])){
			return $CAT['catname'];
		}
		
		$arrparentids = $CAT['arrparentid'].','.$CAT['catid'];
		$arrparentid = explode(',', $arrparentids);
		$pos = '';
		$target = $target ? ' target="_blank"' : '';	
		$CATEGORY = array();
		$ddd = $db->mselect("SELECT catid,catname FROM {$this->full_table} WHERE catid IN ($arrparentids)");
		
		foreach($ddd as $r){
			$CATEGORY[$r['catid']] = $r;
		}
		$last=count($arrparentid)-1;
		foreach($arrparentid as $index=>$catid) {
			if(!$catid || !isset($CATEGORY[$catid])) continue;
			if($index==$last){
				$pos .= $CATEGORY[$catid]['catname'].$str;
			}else{
				//$pos .= '<a href="?r='.$_GET['r'].'&parentid={$catid}"'.'"'.$target.'>'.$CATEGORY[$catid]['catname'].'</a>'.$str;
				$pos .= $CATEGORY[$catid]['catname'].$str;
			}
			
		}
		$_len = strlen($str);
		if($str && substr($pos, -$_len, $_len) === $str) $pos = substr($pos, 0, strlen($pos)-$_len);
		return $pos;
	}
	public function max_catid(){
		$sql="SELECT max(catid) A FROM `{$this->full_table}`";
		$catid=$this->db->get_field($sql);
		// return max(1,$catid);
		return intval($catid);
	}
	public function all_cats($cond=array()){
		return $this->where($cond)->order('listorder asc')->easy_select();
	}
	public function getCatTree($arr,$id=0,$lev=0){
	    $tree = array();
	    foreach($arr as $v) {
	        if($v['parentid'] == $id) {
	            $v['lev'] = $lev;
	            $tree[] = $v;
	            $tree = array_merge($tree,$this->getCatTree($arr,$v['catid'],$lev+1));
	        }
	    }
	    return $tree;
	}
	//判断一个分类是否有子分类
	public function has_child($catid){
		$result=$this->field('catid')->where(array('parentid'=>$catid))->easy_find();
		return $result;
	}
	public function mod_check_ok($catid,$parentid){
		$all_cats = $this->all_cats();
		$sub_cats = $this->getCatTree($all_cats,$catid);
		$ids = array();
		foreach ($sub_cats as $v) {
			$ids[] = $v['catid'];
		}
		#判断所选的父分类是否为当前分类或其后代分类
		if ($parentid == $catid || in_array($parentid, $ids)) return false;
		return true;
	}
	public function del_check_ok($catid){
		$r=$this->has_child($catid);
		return !$r;
	}
	public function my_category_select($name,$catid=0,$label='请选择',$extra=''){
		$all_cats=$this->all_cats();
		$category_arr=$this->getCatTree($all_cats);
		$str="<select name=\"{$name}\" {$extra}>";
		$str.="<option value=\"0\">{$label}</option>";
		foreach($category_arr as $k=>$v){
			if($v['catid']==$catid){
				$sel="selected=\"selected\"";
			}else{
				$sel='';
			}
			$str.="<option value=\"{$v['catid']}\" {$sel}>".str_repeat('&nbsp;',$v['lev']*4)."┖─&nbsp;{$v['catname']}</option>";
		}
		$str.="</select>";
		return $str;
	}
	public function deep_tree_ul($url,$parentid){
		$html='';
		$category=$this->where(array('parentid'=>$parentid))->order('listorder asc')->easy_select();
		if(count($category)==0){
			return array(false,'');
		}
		foreach($category as $key=>$value){
			$son=$this->deep_tree_ul($url,$value['catid']);
			if($son[0]){
				$html.="<li><a href=\"".($url.'&catid='.$value['catid'])."\" target=\"main\">{$value['catname']}</a>";
				$html.="<ul>";
				$html.=$son[1];
				$html.="</ul>";
				$html.="</li>";
			}else{
				$html.="<li><a href=\"".($url.'&catid='.$value['catid'])."\" target=\"main\">{$value['catname']}</a></li>\n";
			}
		}
		return array(true,$html);
	}
	public function cat_is_exists($catname){
		$parentid=$this->parentid;
		if($this->action=='add'){
			$query="select `catid` from `{$this->full_table}` where `catname`=:catname and `parentid`=:parentid ";
			$r=$this->db->get_field($query,array('catname'=>$catname,'parentid'=>$parentid));
			if($r>0){
				return false;
			}
			return true;
		}
		if($this->action=='mod'){
			$catid=$this->catid;
			$query="select `catid` from `{$this->full_table}` where `catname`=:catname and `catid`!=:catid and `parentid`=:parentid ";
			$r=$this->db->get_field($query,array('catname'=>$catname,'catid'=>$catid,'parentid'=>$parentid));
			if($r>0){
				return false;
			}
			return true;
		}
		return false;
	}

}